//
//  WCAppDelegate.m
//  WabbitCode
//
//  Created by William Towe on 1/9/09.
//  Copyright 2009 Revolution Software. All rights reserved.
//

#import "WCAppDelegate.h"
#import "WCAppController.h"
#import "WCMacros.h"
#import "WCDocumentController.h"
#import "WCProject.h"
#import "WCUnsavedFilesWindowController.h"
#import "WCProjectGroup.h"


@implementation WCAppDelegate
#pragma mark NSApplication Delegate
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender {
	return NO;
}

- (void)applicationDidFinishLaunching:(NSNotification *)note {
	if ([[WCDocumentController sharedDocumentController] openMostRecentProject])
		return;
	
	switch (NSUserDefaultsUnsignedIntegerForKey(kWCPrefsGeneralWhenApplicationLaunchesKey)) {
		case WCPGWhenApplicationLaunchesShowNewProjectWindow:
			[[WCDocumentController sharedDocumentController] newProjectAction:nil];
			break;
		case WCPGWhenApplicationLaunchesOpenMostRecentProject:
			[[WCDocumentController sharedDocumentController] openMostRecentProjectAction:nil];
			break;
		case WCPGWhenApplicationLaunchesDoNothing:
		default:
			break;
	}
}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
	NSMutableArray *files = [NSMutableArray array];
	
	for (WCProject *project in [[WCDocumentController sharedDocumentController] allProjects]) {
		[files addObjectsFromArray:[project unsavedTextFiles]];
	}
	
	if (![files count])
		return NSTerminateNow;
	
	NSInteger result = [WCUnsavedFilesWindowController runModalForUnsavedFiles:files type:WCUnsavedFilesTypeBeforeQuitting];
	
	if (result == NSAlertAlternateReturn)
		return NSTerminateCancel;
	return NSTerminateNow;
}
@end
